package main

import (
	"bytes"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

// 测试控制台日志策略
func TestConsoleLogStrategy(t *testing.T) {
	// 创建一个新的日志记录器
	logger := NewLogger()
	logger.UseConsoleStrategy()

	// 重定向标准错误输出到一个字节切片，方便后续检查输出内容
	r, w, _ := os.Pipe()
	old := os.Stderr
	os.Stderr = w

	// 记录一条日志
	LOG(INFO, "test_file.go", 10).Write("Test console log message").End()

	// 关闭写入端，读取输出内容
	w.Close()
	var buf bytes.Buffer
	_, _ = buf.ReadFrom(r)
	os.Stderr = old

	// 检查输出内容是否包含关键信息
	output := buf.String()
	if !strings.Contains(output, "INFO") || !strings.Contains(output, "Test console log message") {
		t.Errorf("Expected console log to contain 'INFO' and 'Test console log message', but got %s", output)
	}
}

// 测试文件日志策略
func TestFileLogStrategy(t *testing.T) {
	logPath := "./test_log/"
	logFile := "test_log.txt"
	// 创建一个新的日志记录器并使用文件日志策略
	logger := NewLogger()
	err := logger.UseFileStrategy(logPath, logFile)
	if err != nil {
		t.Fatalf("Failed to enable file log strategy: %v", err)
	}

	// 记录一条日志
	LOG(ERROR, "test_file.go", 20).Write("Test file log message").End()

	// 关闭文件日志策略中的文件
	if fileStrategy, ok := logger.strategy.(*FileLogStrategy); ok {
		fileStrategy.Close()
	}

	// 读取日志文件内容
	filePath := filepath.Join(logPath, logFile)
	data, err := os.ReadFile(filePath)
	if err != nil {
		t.Fatalf("Failed to read log file: %v", err)
	}

	// 检查日志文件内容是否包含关键信息
	content := string(data)
	if !strings.Contains(content, "ERROR") || !strings.Contains(content, "Test file log message") {
		t.Errorf("Expected file log to contain 'ERROR' and 'Test file log message', but got %s", content)
	}

	// 删除测试日志文件和目录
	_ = os.Remove(filePath)
	_ = os.Remove(logPath)
}

// 测试日志等级转换
func TestLogLevelToString(t *testing.T) {
	tests := []struct {
		level    LogLevel
		expected string
	}{
		{DEBUG, "DEBUG"},
		{INFO, "INFO"},
		{WARNING, "WARNING"},
		{ERROR, "ERROR"},
		{FATAL, "FATAL"},
	}

	for _, test := range tests {
		result := LogLevelToString(test.level)
		if result != test.expected {
			t.Errorf("Expected LogLevelToString(%d) to return %s, but got %s", test.level, test.expected, result)
		}
	}
}
